<template>
  <div v-if="isAuth(['ROOT', 'DRIVER:SELECT'])">
    <el-form :inline="true" :model="searchForm" :rules="dataRule" ref="searchForm">
      <el-form-item prop="name">
        <el-input v-model="searchForm.query.name" placeholder="司机" size="medium" class="input" clearable="clearable"/>
      </el-form-item>

      <el-form-item>
        <el-select v-model="searchForm.query.status" class="input" placeholder="状态" size="medium"
                   clearable="clearable">
          <el-option label="有效" value="3"/>
          <el-option label="作废" value="4"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="loadDataList()" icon="el-icon-search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="uploadContract()" icon="el-icon-s-finance">上传合同</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        cell-style="padding: 2px 0"
        style="width: 100%;"
        size="medium"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
    >
      <el-table-column prop="name" header-align="center" align="center" min-width="80" label="司机"/>
      <el-table-column prop="agreementSn" header-align="center" align="center" min-width="110" label="合同编号"/>
      <el-table-column prop="status" header-align="center" align="center" min-width="180" label="合同状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 3" type="success">有效</el-tag>
          <el-tag v-if="scope.row.status === 4" type="danger">作废</el-tag>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" width="400" label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                     @click="viewContract(scope.row.id)">
            查看合同
          </el-button>
          <el-button type="success" size="small" v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                     @click="downloadContract(scope.row.id)">
            下载合同
          </el-button>
          <el-button type="danger" size="small" v-if="isAuth(['ROOT', 'USER:UPDATE'])"
                     @click="voidContract(scope.row.id)" :disabled="scope.row.status == 4">
            作废
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="searchForm.page"
        :page-sizes="[10, 20, 50]"
        :page-size="searchForm.rows"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!--合同上传弹出框-->
    <el-dialog
        v-model="showContractUpload"
        title="上传合同"
        width="30%"
    >
      <el-form :model="form">
        <el-form-item label="选择司机">
          <el-select v-model="form.driverId" class="m-2" placeholder="请选择司机">
            <el-option
                v-for="d in driverAuthMaterials"
                :label="d.name"
                :value="d.driverId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="form.agreementSn"/>
        </el-form-item>

        <!--合同文件上传-->
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="http://127.0.0.1:10010/fccar/common/app/file/oss/upload"
            name="file"
            accept=".jpg,.jpeg,.png,.gif,.doc,.pdf,.docx"
            multiple
            :on-success="successUploadContract"
            :limit="3"
        >
          <el-button type="primary" size="small">上传合同文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              文件格式: pdf, doc
            </div>
          </template>
        </el-upload>

        <!--合同文件图片上传-->
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="http://127.0.0.1:10010/fccar/common/app/file/oss/upload"
            name="file"
            accept=".jpg,.jpeg,.png,.gif,.doc,.pdf,.docx"
            multiple
            :on-success="successUploadContractPng"
            :limit="3"
        >
          <el-button type="success" size="small">上传合同文件图片，支持预览</el-button>
          <template #tip>
            <div class="el-upload__tip">
              文件格式: jpg, jpeg, png
            </div>
          </template>
        </el-upload>
      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelUpload">取消</el-button>
        <el-button type="primary" @click="confirmUpload">确认</el-button>
      </span>
      </template>
    </el-dialog>

    <!--查看合同-->
    <el-dialog
        v-model="showContract"
        title="合同预览"
        width="40%"
    >
      <img :src="contractPngSrc">
    </el-dialog>
  </div>
</template>
<script>
import $ from 'jquery';
import request from '../utils/request'
import Update from './driver-update.vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {ref} from 'vue'

export default {
  components: {
    Update
  },
  data() {
    return {
      // 高级查询参数
      searchForm: {
        query: {
          name: null,
          agreementSn: null,
          status: null,
        },
        page: 1,
        rows: 10
      },
      expands: [],
      dataList: [], // 合同列表数据
      totalCount: 0, // 总条数
      dataListLoading: false, // 盲等框
      showContractUpload: false, // 合同上传弹框
      contractUrl: '', // 合同文件云端地址
      showContract: false, // 查看合同框
      contractPngSrc: '', // 合同图片云端地址
      // 表单数据
      form: {
        agreementSn: '',
        driverId: '',
      },
      // 所有实名认证材料
      driverAuthMaterials: [],
      // 要展示的文件, 图片放这里
      fileList: [],
      getRowKeys(row) {
        return row.id;
      },
    };
  },
  methods: {

    // 加载列表数据
    loadDataList() {
      // _this保存当前Vue实例
      let _this = this;
      // 遍历查询条件
      for (var prop in _this.searchForm.query) {
        if (_this.searchForm.query[prop] == "") { // 为空字符串就赋值为null, 防止sql查询按空字符去查
          _this.searchForm.query[prop] = null;
        }
      }
      // 分页查询+高级查询合同数据
      _this.post("/driver/manager/driverAggrement/pagelist", _this.searchForm, (res) => {
        let {success, data} = res;
        if (success) { // 请求成功
          _this.totalCount = data.total; // 总条数
          _this.dataList = data.rows; // 列表
        }
      });
    },

    // 上传合同
    uploadContract() {
      let _this = this;
      // 获取所有司机实名材料列表
      _this.getAllDriversAuthMaterials();
      // 开启合同上传弹框
      _this.showContractUpload = true;
      // 清空
      _this.form = {};
      _this.fileList = [];
    },

    // 成功上传合同
    successUploadContract(response, uploadFile, uploadFiles) {
      let _this = this;
      // 保存云端合同文件地址
      _this.contractUrl = response.data;
    },

    // 成功上传合同图片
    successUploadContractPng(response, uploadFile, uploadFiles) {
      let _this = this;
      // 保存云端合同文件地址
      _this.contractPngSrc = response.data;
    },

    // 取消上传
    cancelUpload() {
      let _this = this;
      // 关闭合同上传弹框
      _this.showContractUpload = false;
    },

    // 确认上传合同
    confirmUpload() {
      let _this = this;
      // 定义参数
      let param = {
        driverId: _this.form.driverId, // 司机id
        agreementSn: _this.form.agreementSn, // 合同编号
        contractUrl: _this.contractUrl, // 合同文件云端地址
        contractPngSrc: _this.contractPngSrc, // 合同预览图片云端地址
      }
      // 发送合同保存请求
      _this.post("/driver/manager/driverAggrement/addContract", param, (res) => {
        console.log(res)
        if (res.success) { // 成功
          ElMessage({
            type: 'success',
            message: '保存成功',
          })
          // 获取数据列表
          this.loadDataList();
        } else {
          ElMessage({
            type: 'error',
            message: '保存失败, 请稍后再试',
          })
        }
      })
      // 关闭合同上传弹框
      _this.showContractUpload = false;
    },

    // 查看合同
    viewContract(id) {
      let _this = this;
      // 清空
      _this.contractPngSrc = '';
      _this.showContract = true;
      // 查看当前合同云存储地址
      _this.get("/driver/manager/driverAggrement/getContractPngSrc/" + id, (res) => {
        if (res.data != null && res.data != "") {
          _this.contractPngSrc = res.data;
        } else {
          ElMessage({
            type: 'error',
            message: '预览失败, 请未上传合同图片',
          })
        }

      })

    },

    // 作废合同
    voidContract(id) {
      let _this = this;
      ElMessageBox.confirm(
          '您确认要作废这条合同吗?',
          '再次提醒',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            // 作废合同, 更改合同状态
            _this.post("/driver/manager/driverAggrement/cancelContract/" + id, (res) => {
              if (res.success) {
                ElMessage({
                  type: 'success',
                  message: '作废成功',
                })
                // 获取数据列表
                this.loadDataList();
              } else {
                ElMessage({
                  type: 'error',
                  message: '作废失败, 请稍后再试',
                })
              }
            })
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '您已取消',
            })
          })

    },
    // 下载合同
    downloadContract(id) {
      let _this = this;
      // 下载
      _this.get("/driver/manager/driverAggrement/getContractUrl/" + id, (res) => {
        location.href = res.data;
      })
    },

    // 获取所有司机实名材料
    getAllDriversAuthMaterials() {
      let _this = this;
      _this.post("/driver/manager/driverAuthMaterial/list", (res) => {
        // 保存司机列表
        _this.driverAuthMaterials = res.data;
      })
    }
  },
  created: function () {
    // 获取数据列表
    this.loadDataList();
  }
};
</script>
<style lang="less" scoped="scoped">
@import url('driver.less');
</style>
